package route

import (
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/pprof"
	"github.com/gin-contrib/zap"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	_ "go-base/docs"
	"go-base/src/api/response"
	"go-base/src/configs"
	"go-base/src/core/middle_ware"
	"go-base/src/logs"
	"go.uber.org/zap"
	"time"
)

func Init() *gin.Engine {
	gin.SetMode(configs.Conf.ReleaseMode)
	r := gin.New()
	// 性能分析 - 正式环境不要使用！！！
	if gin.Mode() != gin.ReleaseMode {
		pprof.Register(r)
	}
	//缺失路由
	r.NoRoute(defaultRequest)
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"PUT", "PATCH", "DELETE", "POST", "GET"},
		AllowHeaders:     []string{"*"},
		ExposeHeaders:    []string{"*"},
		AllowCredentials: true,
	}), middle_ware.Recovery())
	//swagger文档
	swaggerUrl := fmt.Sprintf("http://%s:%d%s", configs.Conf.BindIp, configs.Conf.BindPort, configs.Conf.JsonUrl)
	docUrl := fmt.Sprintf("http://%s:%d%s", configs.Conf.BindIp, configs.Conf.BindPort, configs.Conf.IndexUrl)
	logs.Info.Println(docUrl)
	url := ginSwagger.URL(swaggerUrl)
	// 文档界面访问URL
	// http://127.0.0.1:13333/swagger/index.html
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))
	// 使用zap日志库
	r.Use(ginzap.Ginzap(zap.L(), time.RFC3339, true))
	r.Use(ginzap.RecoveryWithZap(zap.L(), true))
	userRoute(r)
	return r
}

// 默认路由
func defaultRequest(c *gin.Context) {
	response.HttpReturn(c, response.RESPONSE_UNKNOWN, nil, "地址不存在")
	return
}
